package weifei.live.simulation;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import org.springframework.stereotype.Component;
import weifei.live.simulation.entity.User;
import weifei.live.simulation.service.AdminerService;
import weifei.live.simulation.service.UserService;




/**
 * 所有token 30分钟清一次
 * */
@Component
public class TokenVerifier
{
    private final AdminerService adminerService = new AdminerService();
    private final UserService userService = new UserService();


    /**
     * @return 验证成功返回对应的 用户数据
     * */
    public User verifyUserToken(String token)
    {
        var user_id = JWT.decode(token).getClaim("userID").asInt();
        if (user_id == null)
            return null;

        var user = this.userService.getUserByID(user_id);
        if (user == null)
            return null;

        try {
            JWTVerifier jwt_verifier = JWT
                    .require(Algorithm.HMAC256(user.getPassword()))
                    .build();
            jwt_verifier.verify(token);
        }
        catch (JWTVerificationException e) { return null; }
        return user;
    }


    public boolean verifyAdminerToken(String token)
    {
        var adminer_id = JWT.decode(token).getClaim("adminerID").asInt();
        if (adminer_id == null)
            return false;

        var adminer = this.adminerService.getAdminerByID(adminer_id);
        if (adminer == null)
            return false;

        try {
            JWTVerifier jwt_verifier = JWT
                    .require(Algorithm.HMAC256(adminer.getPassword()))
                    .build();
            jwt_verifier.verify(token);
        }
        catch (JWTVerificationException e) { return false; }
        return true;
    }



    public static Integer getUserIDByToken(String token)
    {
        return JWT.decode(token).getClaim("userID").asInt();
    }


    public static Integer getAdminerIDByToken(String token)
    {
        return JWT.decode(token).getClaim("adminerID").asInt();
    }


}


